﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using BusinessLogic;
using BusinessEntities;


namespace RevRaider
{
    public partial class ReportGeneratorForm : Form
    {

        public ReportGeneratorForm()
        {
            InitializeComponent();
                        
            RetrieveArmoryRaidersProcess.DoWork += new DoWorkEventHandler(GenerateAllMembersReport);
            RetrieveArmoryRaidersProcess.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
            RetrieveArmoryRaidersProcess.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);

            ArmoryProgress.ArmoryProgressed += new ArmoryProgress.NotificationsEventHandler(QueryProgressed);
        }

        private void ReportGeneratorForm_Load(object sender, EventArgs e)
        {
            dtpLastActive.Value = DateTime.Now.AddDays(-7);
        }     

        private void btnReport_Click(object sender, EventArgs e)
        {
            if (RetrieveArmoryRaidersProcess.IsBusy == false && ValidateForm() == true)
            {                
                ProcessingLabel.Visible = true;
                ProcessingLabel.Text = "Processing...";
                RetrieveArmoryRaidersProcess.RunWorkerAsync();
            }
            else
            {
                ProcessingLabel.Text = "Have patience young padawan!";
            }
        }

        delegate Comparison<Raider> rankCompaerer();
        
        private void GenerateAllMembersReport(object sender, DoWorkEventArgs e)
        {
            try
            {
                Armory armory = new Armory();
                List<Raider> members;
                SearchCriteria criteria = new SearchCriteria();

                criteria.ServerName = txtServer.Text.Trim();
                criteria.GuildName = txtGuild.Text.Trim();
                criteria.MinLevel = Convert.ToInt32(nudMinLevel.Value);
                criteria.MinItemsAvgLevel = Convert.ToInt32(nudItemsAvg.Value);
                criteria.LastUpdated = dtpLastActive.Value;
                
                if (txtServer.Text.Trim().Equals("Sunstrider") && txtGuild.Text.Trim().Equals("Revenant"))
                {
                    MessageBox.Show("You have chosen to display data for the Guild Revenant of Sunstrider, only raiders information will be shown, excluding the ranks [Valued Guildie], [Alt] and [Council Alt].");
                    ArmoryProgress.Notify(new ArmoryNotificationEventArgs("Querying Revenant raiders"));
                    members = armory.GetRaiders(criteria);
                }
                else
                {
                    ArmoryProgress.Notify(new ArmoryNotificationEventArgs("Querying all members"));
                    members = armory.GetAllMembers(criteria);
                }
                                
                members.Sort(Raider.CompareByRank);
                Report.GenerateAllMembersReport(members);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            // First, handle the case where an exception was thrown.
            if (e.Error != null)
            {
                MessageBox.Show(e.Error.Message);
            }
            else if (e.Cancelled)
            {
                ProcessingLabel.Text = "Canceled";
            }
            else
            {
                ProcessingLabel.Text = "Proccess complete";
                System.Diagnostics.Process.Start(@"Revenant Members.csv");
            }
        }

        private void txtServer_Validating(object sender, CancelEventArgs e)
        {
            ValidateServerInput();
        }

        private bool ValidateForm()
        {
            bool isServerNameValid, isGuildNameValid;
            isServerNameValid = ValidateServerInput();
            isGuildNameValid = ValidateGuildInput();

            return (isServerNameValid == true && isGuildNameValid == true);
        }

        private bool ValidateServerInput()
        {
            bool isValid = true;

            if (txtServer.Text.Equals(string.Empty))
            {
                isValid = false;
                errorProvider1.SetError(txtServer, "Please fill in the server name");
            }
            else
            {
                errorProvider1.SetError(txtServer, "");
            }

            return isValid;
        }

        private bool ValidateGuildInput()
        {
            bool isValid = true;

            if (txtGuild.Text.Equals(string.Empty))
            {
                isValid = false;
                errorProvider1.SetError(txtGuild, "Please fill in the guild name");
            }
            else
            {
                errorProvider1.SetError(txtGuild, "");
            }

            return isValid;
        }
        
        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            ArmoryNotificationEventArgs userState = (ArmoryNotificationEventArgs)(e.UserState);
            txtProgressReport.AppendText(DateTime.Now.ToString("[hh:mm:ss]  "));
            txtProgressReport.AppendText(userState.Message);
            txtProgressReport.AppendText(Environment.NewLine);
        }

        private void QueryProgressed(ArmoryNotificationEventArgs e)
        {
            RetrieveArmoryRaidersProcess.ReportProgress(0, e);

        }

    }
}
